<template>
  <el-form :model="form" :rules="rules" ref="form" class="demo-ruleForm">
    <el-form-item prop="username">
      <el-input
        v-model="form.username"
        placeholder="请输入用户"
        @focus="verification('username')"
      ></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="form.password"
        placeholder="请输入密码"
        @focus="verification('password')"
        type="password"
      ></el-input>
    </el-form-item>
    <p class="form-text">
      <nuxt-link to="#">忘记密码</nuxt-link>
    </p>
    <el-button type="primary" class="submit" @click="handlerLogin"
      >登录</el-button
    >
  </el-form>
</template>

<script>
import { login } from "@/utils/indexApi.js";
export default {
  data() {
    return {
      form: {
        username: "13800138000",
        password: "123456",
      },
      // 表单规则
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 用户输入不正确时重新获取焦点验证信息就重新验证
    verification(prop) {
      this.$refs.form.clearValidate(prop);
    },

    // 点击登录的处理
    handlerLogin() {
      this.$refs.form.validate(async (props) => {
        // 如果进行验证成功则在去发送请求;
        if (props) {
          // 使用在store 中封装的请求
          this.$store.dispatch("userstore/login", this.form);
          this.$router.push({ name: "index" });
          this.$message.success("登录成功");
          // let res = await login(this.form).catch((err) => {});
          // console.log(res);
          // if (res && res.data.token) {
          //   this.$message.success("登录成功");
          //   // 跳转到首页
          //
          //   // 把数据储存到store 中 通过 $store.commit(模块名/函数名, 要储存的数据)
          //   this.$store.commit("userstore/setUserInfo", res.data);
          // }
        }
      });
    },
  },
};
</script>

<style scoped lang="less">
.form {
  padding: 25px;
}

.form-item {
  margin-bottom: 20px;
}

.form-text {
  font-size: 12px;
  color: #409eff;
  text-align: right;
  line-height: 1;
}

.submit {
  width: 100%;
  margin-top: 10px;
}
</style>